#include "jpasswdlineedit.h"
#include <QToolButton>
#include <QHBoxLayout>
#include <QEvent>

namespace QTE
{

class Q_DECL_HIDDEN JPasswdLineEditPrivate
{
public:
	JPasswdLineEditPrivate(JPasswdLineEdit &ple);
	~JPasswdLineEditPrivate() {}

public:
	QToolButton *pb_echo;
	QHBoxLayout *layout;
};

JPasswdLineEditPrivate::JPasswdLineEditPrivate(JPasswdLineEdit &ple) :
	pb_echo(new QToolButton(&ple)),
	layout(new QHBoxLayout())
{
	pb_echo->setText("隐藏");
	pb_echo->setStyleSheet("QToolButton{color:rgb(160,160,160);"
						   "background-color:rgba(0,0,0,0); border: 0px;}"
						   "QToolButton:pressed{color:rgb(200,90,90);}");

	pb_echo->setCheckable(true);
	pb_echo->setChecked(false);
	pb_echo->setFocusPolicy(Qt::NoFocus);

#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
	layout->setMargin(0);
#else //qt6
	layout->setSpacing(0);
#endif //qt6

	layout->setContentsMargins(0,0,0,0);
	layout->addWidget(pb_echo, 0, Qt::AlignRight);
	ple.setLayout(layout);
}

/*------------------------------------------------------------------------------*/

JPasswdLineEdit::JPasswdLineEdit(QWidget *parent) :
	QLineEdit(parent),
	d_ptr(new JPasswdLineEditPrivate(*this))
{
	setEchoMode(QLineEdit::Password);
	d_ptr->pb_echo->setMinimumHeight(minimumHeight());

	connect(d_ptr->pb_echo, &QToolButton::clicked, [this](bool flag)
	{
		if( flag )
		{
			QLineEdit::setEchoMode(Normal);
			d_ptr->pb_echo->setText("可见");
		}
		else
		{
			QLineEdit::setEchoMode(Password);
			d_ptr->pb_echo->setText("隐藏");
		}
	});
}

JPasswdLineEdit::~JPasswdLineEdit()
{
	delete d_ptr;
}

bool JPasswdLineEdit::allowViewPasswd() const
{
	return not d_ptr->pb_echo->isHidden();
}

bool JPasswdLineEdit::passwdVisible() const
{
	return QLineEdit::echoMode() == Normal;
}

void JPasswdLineEdit::setEchoMode(EchoMode mode)
{
	if( d_ptr->pb_echo->isHidden() and mode == Normal )
		return ;
	QLineEdit::setEchoMode(mode);
}

void JPasswdLineEdit::setPasswdVisible(bool visible)
{
	if( visible )
	{
		if( not d_ptr->pb_echo->isHidden() )
		{
			QLineEdit::setEchoMode(Normal);
			d_ptr->pb_echo->setText("可见");
		}
	}
	else
	{
		QLineEdit::setEchoMode(Password);
		d_ptr->pb_echo->setText("隐藏");
	}
}

void JPasswdLineEdit::setAllowViewPasswd(bool enable)
{
	if( enable )
		d_ptr->pb_echo->show();
	else
	{
		QLineEdit::setEchoMode(Password);
		d_ptr->pb_echo->setText("隐藏");
		d_ptr->pb_echo->setChecked(false);
		d_ptr->pb_echo->hide();
	}
}

bool JPasswdLineEdit::event(QEvent *event)
{
	if( event->type() == QEvent::FontChange )
		d_ptr->pb_echo->setFont(font());

	return QLineEdit::event(event);
}

} //namespace QTE
